package qs.openxt.libs.plugins;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import qs.openxt.libs.R;
import qs.openxt.libs.cv.Camera;
import qs.openxt.libs.cv.Video;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.remoting.Upload;
import qs.openxt.libs.remoting.Upload.OnActionListener;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.JSONUtil;
import qs.openxt.libs.util.PictureUtil;
import qs.openxt.libs.util.StringUtil;

public class WebcamPlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
	private Camera camera = null;
	public static final int RETURNTYPE_CAMERA = 1; // Take picture from camera
	public static final int RETURNTYPE_VIDEO = 2; // Take picture from camera
	public static final int RETURNTYPE_ALBUM = 3; // Take picture from camera
	private JSONArray args = null;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:{
					callbackContext.success((String)msg.obj);
					break;
				}
				case 3:{
					Toast.makeText(cordova.getActivity(), "文件上传失败", Toast.LENGTH_SHORT).show();
					break;
				}
			default:
				break;
			}
		};
	};

	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doWebcamApp".equals(action)) {
			if(!ActivityUtil.isNetworkAvailable(cordova.getActivity())){
				Toast.makeText(cordova.getActivity(), cordova.getActivity().getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
				return false;
			}
			if (args == null || args.length() == 0) {
				Toast.makeText(cordova.getActivity(), "请设置通讯参数", Toast.LENGTH_SHORT).show();
				return false;
			}
			this.args = args;
			String wc_type = args.optString(0);
			if ("photo".equals(wc_type)) {
				camera = new Camera(WebcamPlugins.this);
				camera.takePicture(RETURNTYPE_CAMERA, Camera.JPEG);
				return true;
			}else if ("album".equals(wc_type)) {
				camera = new Camera(WebcamPlugins.this);
				camera.getImage(RETURNTYPE_ALBUM, Camera.JPEG);
				return true;
			} else if ("video".equals(wc_type)) {
				Intent intent = new Intent();
				intent.setClass(cordova.getActivity(), Video.class);
				cordova.startActivityForResult(WebcamPlugins.this, intent, RETURNTYPE_VIDEO);
				return true;
			}else
				return false;
		}else 
			return false;
	}

	/**
	 * Called when the camera view exits.
	 * 
	 * @param requestCode
	 *            The request code originally supplied to
	 *            startActivityForResult(), allowing you to identify who this
	 *            result came from.
	 * @param resultCode
	 *            The integer result code returned by the child activity through
	 *            its setResult().
	 * @param intent
	 *            An Intent, which can return result data to the caller (various
	 *            data can be attached to Intent "extras").
	 */
	public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		if ((requestCode == RETURNTYPE_CAMERA || requestCode == RETURNTYPE_VIDEO || requestCode == RETURNTYPE_ALBUM) && resultCode == Activity.RESULT_OK) {
			try {
				String uri = null;
				if (requestCode == RETURNTYPE_CAMERA)
					uri = camera.processResultFromCamera(intent);
				else if (requestCode == RETURNTYPE_VIDEO) {
					uri = intent.getStringExtra("path");
				} else if (requestCode == RETURNTYPE_ALBUM) {
					uri = camera.processResultFromGallery(intent);
				} else
					return;

                final String path = uri;
                boolean showConfirm = "false".equals(args.optString(3)) ? false : true;

                if(showConfirm){
                    ActivityUtil.showConfirmDialog(cordova.getActivity(), "立即上传文件吗？", "确认", "取消", new ConfirmDialogListener() {
                        @Override
                        public void onOK() {
                            try{
                                doU(path);
                            }catch (Exception e){

                            }
                        }

                        @Override
                        public void onCancel() {//返回本地地址
                            Wait.sharedInstance().start(cordova.getActivity(), "正在处理图片...，请稍候");
                            cordova.getThreadPool().execute(new Runnable() {
                                @Override
                                public void run() {
                                    com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                                    try{
                                        array.add(PictureUtil.getFilePath(path));

                                        Message message = new Message();
                                        message.what = 1;
                                        message.obj = array.toString();
                                        mHandler.sendMessage(message);
                                    }catch (Exception e){
                                    }finally {
                                        Wait.sharedInstance().stop();
                                    }
                                }
                            });
                        }
                    });
                }else{
                    /*
                    doU(path);*/
                    Wait.sharedInstance().start(cordova.getActivity(), "正在处理图片...，请稍候");
                    cordova.getThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                            try{
                                array.add(PictureUtil.getFilePath(path));

                                Message message = new Message();
                                message.what = 1;
                                message.obj = array.toString();
                                mHandler.sendMessage(message);
                            }catch (Exception e){
                            }finally {
                                Wait.sharedInstance().stop();
                            }
                        }
                    });
                }
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

    private void doU(final String path) throws Exception{
        JSONObject params = new JSONObject();
        params.put("file", path);
        params.put("url", args.optString(1));
        Object val = args.opt(2);
        if (val != null) {
            if (val instanceof org.json.JSONObject) {
                params.put("param", JSONUtil.toJSON((org.json.JSONObject) val));
            } else if (!StringUtil.isNull(val)) {
                String[] split = val.toString().split("\\&");
                if (split.length > 1) {
                    JSONObject param = new JSONObject();
                    for (int i = 0; i < split.length; i++) {
                        String[] $split = split[i].split("\\=");
                        if ($split.length == 2)
                            param.put($split[0], $split[1]);
                    }
                    params.put("param", param);
                }
            }
        }

        Upload upload = new Upload(cordova.getActivity(), new OnActionListener() {
            @Override
            public void onActionCompleted(final String reVal) {
                Message message = new Message();
                message.what = 1;
                message.obj = reVal;
                mHandler.sendMessage(message);
            }

            @Override
            public void onActionError() {
                Message message = new Message();
                message.what = 3;
                mHandler.sendMessage(message);
            }
        });
        upload.doRequest(params);
    }
}
